package main.java.com.lx.tools.trans

import com.google.gson.Gson
import java.io.BufferedReader
import java.io.InputStreamReader
import java.net.HttpURLConnection
import java.net.URL
import java.net.URLDecoder
import java.net.URLEncoder
import java.security.MessageDigest
import java.security.NoSuchAlgorithmException
import java.util.*

class TransApi {

    companion object {
        private val TRANS_API_HOST = "http://api.fanyi.baidu.com/api/trans/vip/translate"

        private val appId = "20171117000096168"
        private val securityKey = "YttlH7Qxmucn5Rg5ytnc"

        fun getTransResult(query: String, to: String): String? {
            val requestUrl = getUrlWithQueryString(TRANS_API_HOST, buildParams(query, to))
            val result = sendGet(requestUrl)
            val mapResult = Gson().fromJson(result, Map::class.java)
            val listDst: List<Map<String, String>> = (mapResult["trans_result"] as List<*>).filterIsInstance<Map<String, String>>()
            return listDst[0]["dst"]
        }

        private fun buildParams(query: String, to: String): Map<String, String> {
            val params = HashMap<String, String>()
            params.put("q", query)
            params.put("from", "auto")
            params.put("to", to)
            params.put("appid", appId)
            // 随机数
            val salt = System.currentTimeMillis().toString()
            params.put("salt", salt)
            // 签名
            val src = appId + query + salt + securityKey // 加密前的原文
            params.put("sign", md5(src))
            return params
        }

        private fun md5(input: String): String {
            try {
                val instance: MessageDigest = MessageDigest.getInstance("MD5")//获取md5加密对象
                val digest: ByteArray = instance.digest(input.toByteArray())//对字符串加密，返回字节数组
                val sb = StringBuffer()
                for (b in digest) {
                    val i: Int = b.toInt() and 0xff//获取低八位有效值
                    var hexString = Integer.toHexString(i)//将整数转化为16进制
                    if (hexString.length < 2) {
                        hexString = "0" + hexString//如果是一位的话，补0
                    }
                    sb.append(hexString)
                }
                return sb.toString()
            } catch (e: NoSuchAlgorithmException) {
                e.printStackTrace()
            }
            return ""
        }

        private fun sendGet(url: String): String {
            val obj = URL(url)
            with(obj.openConnection() as HttpURLConnection) {
                requestMethod = "GET"
                BufferedReader(InputStreamReader(inputStream)).use {
                    val response = StringBuffer()
                    var inputLine = it.readLine()
                    while (inputLine != null) {
                        response.append(inputLine)
                        inputLine = it.readLine()
                    }
                    return response.toString()
                }
            }
        }

        private fun getUrlWithQueryString(url: String, params: Map<String, String>): String {
            val builder = StringBuilder(url)
            if (url.contains("?")) {
                builder.append("&")
            } else {
                builder.append("?")
            }
            for ((i, key) in params.keys.withIndex()) {
                val value = params[key]
                if (i != 0) {
                    builder.append('&')
                }
                builder.append(key)
                builder.append('=')
                builder.append(URLEncoder.encode(value, "utf-8"))
            }
            return builder.toString()
        }
    }
}